/**
 * 返回格式为`00:00:00`的时间
 * @param {Number} milliSeconds 毫秒时间
 * @returns {String} 00:00:00
 */
export const time = (milliSeconds = 0) => {
  const dayTime = 24 * 60 * 60 * 1000;
  if (milliSeconds > dayTime) {
    return "-- : -- : --";
  }

  const standard = new Date("2000-1-1 00:00:00");
  const relative = new Date(standard.getTime() + milliSeconds);
  const H = relative.getHours();
  const M = relative.getMinutes();
  const S = relative.getSeconds();

  return [H, M, S].map((t) => ("0" + t).slice(-2)).join(":");
};

/**
 * 保留定长，不足补零
 * @param {String | Number} num
 * @param {Number} len 要保留的长度
 * @returns {String}
 */
const cut = (num, len) => {
  return num.toString().padStart(len, "0").slice(-len);
};

export const DATE_TIME_FORMAT = "YYYY-MM-DD HH:mm:ss";
export const DATE_FORMAT = "YYYY-MM-DD";
export const DATE_FORMAT_TM = "YYYY-MM-DD HH:mm";

/**
 * 格式化日期
 * @param {Date} date
 * @param {String} format
 */
export const dateFormat = (date = new Date(), format = DATE_TIME_FORMAT) => {
  const Y = date.getFullYear();
  const M = date.getMonth() + 1;
  const D = date.getDate();
  const H = date.getHours();
  const h = H % 12;
  const m = date.getMinutes();
  const s = date.getSeconds();

  return format
    .replace(/Y{4,}/g, cut(Y, 4))
    .replace(/Y{3}/g, cut(Y, 3))
    .replace(/Y{2}/g, cut(Y, 2))
    .replace(/Y/g, cut(Y, 4))
    .replace(/M{2,}/g, cut(M, 2))
    .replace(/M/g, M)
    .replace(/D{2,}/g, cut(D, 2))
    .replace(/D/g, D)
    .replace(/H{2,}/g, cut(H, 2))
    .replace(/H/g, H)
    .replace(/h{2,}/g, cut(h, 2))
    .replace(/h/g, h)
    .replace(/m{2,}/g, cut(m, 2))
    .replace(/m/g, m)
    .replace(/s{2,}/g, cut(s, 2))
    .replace(/s/g, s);
};
